package com.w1.security.handler.failHandler;

import com.alibaba.fastjson.JSON;
import com.w1.security.domain.ResponseResult;
import com.w1.security.utiles.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 授权失败处理类
 * @author mingyifan
 * @date 2022-02-17 09:38
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler, Serializable
{
    @Value("${securityProperties.auto403}")
    private String auto403;
    private static final long serialVersionUID = -8970718117437077606L;
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        if (request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            //ajax请求
            ResponseResult responseResult = new ResponseResult(HttpStatus.FORBIDDEN.value(),"权限不足");
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
        }else{
            response.sendRedirect(auto403);
        }
    }
}